package com.itheima.mp.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 张文接
 * @version 1.0
 * @createTime 2024/6/13 22:08
 */
@Slf4j
@Repository
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public void deductBalance(Long id, Integer money) {
        User user = this.getById(id);
        if (user == null || user.getStatus() == UserStatus.FREEZE) {
            throw new RuntimeException("用户状态异常");
        }
        if (money > user.getBalance()) {
            throw new RuntimeException("用户余额不足");
        }
        int i = user.getBalance() - money;
        boolean update = this.lambdaUpdate()
                .set(User::getBalance, money)
                .set(i == 0, User::getStatus, 2)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance())
                .update();
        if (!update) {
            throw new RuntimeException("减扣失败");
        }
//
//        baseMapper.deductBalance(id, money);
    }

    @Override
    public List<User> queryUser(String name, Integer status, Integer maxBalance, Integer minBalance) {
        return this.lambdaQuery()
                .like(StringUtils.hasText(name), User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .gt(minBalance != null, User::getBalance, minBalance)
                .lt(maxBalance != null, User::getBalance, maxBalance)
                .list();
    }

    @Override
    public PageDTO<UserVO> queryUsersPage(UserQuery userQuery) {
        Page<User> page = userQuery.toMpPageDefaultSortByUpdateTime();
        Page<User> userPage = this.lambdaQuery()
                .like(StringUtils.hasText(userQuery.getName()), User::getUsername, userQuery.getName())
                .eq(userQuery.getStatus() != null, User::getStatus, userQuery.getStatus())
                .gt(userQuery.getMinBalance() != null, User::getBalance, userQuery.getMinBalance())
                .lt(userQuery.getMaxBalance() != null, User::getBalance, userQuery.getMaxBalance())
                .page(page);
        return PageDTO.of(userPage, UserVO.class);
    }

    @Override
    @Cacheable(value = "user")
    public User queryUserById(Long id) {
        return this.getById(id);
    }
}
